#!/usr/bin/env python
#
# Copyright 2008 Allen Hutchison (allen@hutchison.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $URL$
__version__ = "$Rev$"
__author__ = "Allen Hutchison (allen@hutchison.org)"

"""Return the current status of the specified item.

URL Args: format (xml|json) - The format for the response

This script handles all requests for status.severedelays.org/*/current when
called it will use the preceeding parts of the URL to determine the correct 
data to return. Currently we only support /uk-lon/current.
"""

import datetime
import logging
import os

from lib.current_status import CurrentStatus
from lib.request_handler import BaseRequest

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class CurrentPage(BaseRequest):
  def get(self, path):
    cs = CurrentStatus()
    update = cs.getLines()[0].update
    expire = update + datetime.timedelta(minutes=5)
    format = self.request.get('format')
    logging.info('Page Request for format=%s and path=%s' % 
      ((format or 'None'), path))
    if ('xml' == format):
      template_values = {'cs': cs,
                         'update': update}
      self.generate(template_name='current.xml', expires=expire,
                    template_values=template_values, content_type='text/xml')
    elif ('json' == format):
      self.generate(expires=expire, content_type='application/json',
                    data=simplejson.dumps(cs.getDict()))
    else:
      template_values = {'cs': cs,
                         'update': update}
      self.generate(template_name='current.html', expires=expire,
                    template_values=template_values)
    

application = webapp.WSGIApplication([('/(.*/)*current', CurrentPage)])

def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
  